/**
  * @description 获取用户信息
  * @author unhejing (成都-敬宇杰)
  * @date 2020-02-27 上午11:09:40
  */
 const {
 	validateToken
 } = require('../../utils/validateToken.js')
 'use strict';
 const db = uniCloud.database()
 exports.main = async (event, context) => {
 	//event为客户端上传的参数
 	console.log('event:' + event)
 	let tokenRes = await validateToken(event.token)
 	if (tokenRes.code != 0) {
 		return tokenRes;
 	}
 	event.user_id = tokenRes.user_id;
	//event.user_id = "4";
 	if (event.user_id == '' || !event.user_id) {
 		return {
 			success: false,
 			code: -1,
 			msg: '参数错误，缺少用户id'
 		}
 	}

 	let currentTime = new Date().getTime()
 	const collection = db.collection('user_info')
 	let res = await collection.where({user_id:event.user_id}).get();
	console.log("查询结果："+JSON.stringify(res))
 	if (res.data && res.data.length > 0) {
 		return {
 			success: true,
 			code: 0,
 			msg: '成功',
			data:res.data[0]
 		}
 	}
 	let updateRes;
 	if (!res.data || res.data.length == 0) {
 		console.log("用户信息表不存在，新建")
 		updateRes = await collection.add({
			name:"",// 联系人姓名
			address:"",// 收货地址
			phone:"",// 联系人电话
 			user_id: event.user_id, // 关联用户表的用户id
 			create_time: currentTime, // 时间戳，创建时间
 			update_time: currentTime // 时间戳，更新时间
 		})
 	}
 	console.log("新增用户信息返回参数：" + JSON.stringify(updateRes))
 	if (updateRes.id) {
		let addUser = await collection.doc(updateRes.id).get();
 		return {
 			success: true,
 			code: 0,
 			msg: '成功',
			data:addUser.data[0]
 		}
 	}
 	return {
 		success: false,
 		code: -1,
 		msg: '服务器内部错误'
 	}
 };
